<template>
  <div>
    <el-upload
      :accept="accept"
      :file-list="fileList"

      :action="uploadUrl"
      :data="{folder}"
      :before-upload="beforeUpload"

      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :on-preview="handlePreview"
      :on-exceed="handleExceed"
    >
      <el-button type="success" size="small" icon="el-icon-plus" />
      <div slot="tip" class="el-upload__tip">{{ tip }}</div>
    </el-upload>

    <el-dialog v-if="dialogVisible" :visible.sync="dialogVisible">
      <a v-for="(file,index) in fileList" :key="index" target="_blank" width="100%" :href="file.url" :alt="file.name">
        {{ file.name }}
      </a>
    </el-dialog>
  </div>
</template>

<script>

import { uploadUrl } from '@/api/file/upload'

export default {
  name: 'SingleUpload',
  props: {
    value: {
      type: String,
      default: ''
    },
    // 文件大小限制，默认5M
    sizeLimit: {
      type: Number,
      default: 5
    },
    folder: {
      type: String,
      default: 'common'
    },
    accept: {
      type: String,
      default: '.png,.jpg,.jpeg'
    },
    tip: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      showFileList: false,
      uploadUrl,
      dialogVisible: false
    }
  },
  computed: {
    fileList() {
      const fileList = []

      if (this.value) {
        for (let i = 0; i < this.value.length; i++) {
          fileList.push({
            name: this.value[i].name,
            url: this.value[i].url
          })
        }
      }

      return fileList
    }
  },
  methods: {
    handleRemove(file, fileList) {
      this.emitInput(fileList)
    },
    emitInput(val) {
      this.$emit('input', val)
    },
    handlePreview(file) {
      this.dialogVisible = true
    },
    beforeUpload(file) {
      // 校验文件大小
      const sizeLimit = this.sizeLimit
      const isLtSizeLimit = file.size / 1024 / 1024 < sizeLimit
      if (!isLtSizeLimit) {
        this.$message.error(`上传图片大小不能超过 ${sizeLimit}MB!`)
      }

      return isLtSizeLimit
    },
    handleUploadSuccess(res, file) {
      this.showFileList = true
      this.fileList.pop()
      this.fileList.push({ name: res.data.filename, url: res.data.absoluteUrl })
      this.emitInput(this.fileList)
    }
  }

}
</script>

<style scoped>

</style>
